﻿using Microsoft.Extensions.Caching.Memory;
using MyProjectControlApplication.Interfaces;

namespace MyProjectControlApplication
{
    public class CacheServiceControl: ICacheService
    {
        private readonly IMemoryCache _memoryCache;
        private readonly MemoryCacheEntryOptions _cacheOptions;

        public CacheServiceControl(IMemoryCache memoryCache)
        {
            _memoryCache = memoryCache;
            _cacheOptions = new MemoryCacheEntryOptions
            {
                AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1),
                SlidingExpiration = TimeSpan.FromHours(24),
                Priority = CacheItemPriority.High
            };
        }
        public T GetData<T>(string key)
        {
            try
            {
                return _memoryCache.Get<T>(key);
            }
            catch (Exception ex)
            {
                throw new Exception($"Error retrieving data from cache: {ex.Message}");
            }
        }

        public bool SetData<T>(string key, T value, TimeSpan? expirationTime = null)
        {
            try
            {
                if (expirationTime != null)
                {
                    _cacheOptions.AbsoluteExpirationRelativeToNow = expirationTime;
                }

                _memoryCache.Set(key, value, _cacheOptions);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"Error saving data to cache: {ex.Message}");
            }
        }

        public bool RemoveData(string key)
        {
            try
            {
                _memoryCache.Remove(key);
                return true;
            }
            catch (Exception ex)
            {
                throw new Exception($"Error removing data from cache: {ex.Message}");
            }
        }
    }
}
